package net.zjitc.controller.admin;

import net.zjitc.pojo.Category;
import net.zjitc.pojo.Product;
import net.zjitc.service.CategoryService;
import net.zjitc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author admin
 * @Date 2019/4/3 10:36
 */
@Controller
@RequestMapping("/manage/product/")
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    CategoryService categoryService;

    @RequestMapping("add")
    public String addProduct(Product product,
                             @RequestParam(required = false,value = "pfile") MultipartFile file,
                             HttpServletRequest request){

        //数据库存的是什么？路径
        //文件存在哪里？磁盘（一定不在数据库中）当前项目下
        String path = request.getServletContext().getRealPath("/product/");
        if (file != null){
            //文件存的目录，如果不存在则要创建此目录
            File dir = new File(path);
            if (!dir.exists()){
                dir.mkdirs();
            }
            //文件名称(uuid+文件名)
            String fileName = UUID.randomUUID().toString()+"-"+ file.getOriginalFilename();
            //创建目录下的文件
            File filePath = new File(dir,fileName);

            try {
                //将上传的文件写入目录文件（本地）
                file.transferTo(filePath);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("写入失败");
            }
            //为product设置文件存储的路径，以便于在于数据库中
            product.setImgurl("/product/"+fileName);
        }
        //写入数据库

        return null;
    }

   public String findAll(Model model){
       List<Product> productList = productService.findAll();
       List<Category> categoryList = categoryService.findAllCategory();
       model.addAttribute("plist",productList);
       model.addAttribute("clist",categoryList);
       return "...list.jsp";

   }
}
